package com.walk.zworld.ui.activity.my

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.PopupWindow
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jeremyliao.liveeventbus.LiveEventBus
import com.walk.zworld.R
import com.walk.zworld.mvvm.vm.TodoActivityViewModel
import com.walk.zworld.view.SwipeItemLayout
import com.base.lib.base.view.BaseMvvmListActivity
import com.base.lib.httpUtils.TodoBean
import kotlin.collections.set

class TodoActivity : BaseMvvmListActivity<TodoBean, TodoActivityViewModel, TodoActivity.TodoAdapter>() {

    companion object {
        const val DEAL_SUCCESS = 1
    }

    private lateinit var toolbarTitle: TextView
    private lateinit var dataMap: MutableMap<String, Any>
    private lateinit var popWindow: PopupWindow

    override fun onBindAdapter(): Class<TodoAdapter> = TodoAdapter::class.java

    override fun onBindViewModel(): Class<TodoActivityViewModel> = TodoActivityViewModel::class.java

    override fun initView() {
        dataMap = mutableMapOf()
        mRecyclerView.run {
            addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(this@TodoActivity))
        }
        mAdapter.run {
            //item使用的自定义的SwipeItemLayout，会导致item点击事件无效，所以在ChildClick添加item点击事件
            setOnItemClickListener { adapter, view, position -> }
            addChildClickViewIds(R.id.item_todo_done, R.id.item_todo_delete, R.id.rl_item_todo)
            setOnItemChildClickListener { adapter, view, position ->
                var status = data[position]
                when (view.id) {
                    R.id.rl_item_todo -> {
                        val intent = Intent(this@TodoActivity, AddTodoActivity::class.java)
                        intent.putExtra("id", data[position].id)
                        intent.putExtra("type", "edit")
                        intent.putExtra("dateStr", data[position].dateStr)
                        intent.putExtra("title", data[position].title)
                        intent.putExtra("priority", data[position].priority)
                        intent.putExtra("content", data[position].content)
                        startActivityForResult(intent, DEAL_SUCCESS)
                    }
                    R.id.item_todo_done -> {
                        if (data[position].status == 0) {
                            updateTodoById(data[position].id, 1)
                            if (toolbarTitle.text == "TODO") {
                                status.status = 1
                                setData(position, status)
                            } else adapter.removeAt(position)
                        } else {
                            updateTodoById(data[position].id, 0)
                            if (toolbarTitle.text == "TODO") {
                                status.status = 0
                                setData(position, status)
                            } else adapter.removeAt(position)
                        }
                    }
                    R.id.item_todo_delete -> {
                        deleteTodoById(data[position].id)
                        adapter.removeAt(position)
                    }
                }
            }
        }
//        floating_action_btn.run {
//            setOnClickListener {
//                if (!this@TodoActivity::popWindow.isInitialized) initPopWindow(it)
//                else if (popWindow.isShowing) popWindow.dismiss()
//                else popWindow.showAsDropDown(it, -1, -585)
//            }
//        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initData() {
        toolbarTitle = setTop("TODO")
        setRight(R.drawable.add) {
            val intent = Intent(this, AddTodoActivity::class.java)
            intent.putExtra("type", "new")
            startActivityForResult(intent, DEAL_SUCCESS)
        }
        onRefreshEvent()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initPopWindow(view: View) {
        val popView = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null, false)
        popWindow = PopupWindow(
            popView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        )
        popWindow.run {
            animationStyle = R.anim.fade_in
            isTouchable = true
            setTouchInterceptor { view, motionEvent ->
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                return@setTouchInterceptor false
            }
            setBackgroundDrawable(ColorDrawable(resources.getColor(R.color.white)))
            showAsDropDown(view, -1, -585)
            popView.findViewById<View>(R.id.tv_pop_all).setOnClickListener {
                dataMap.clear()
                params = dataMap;
                onRefreshEvent()
                popWindow.dismiss()
                toolbarTitle.text = "TODO"
            }
            popView.findViewById<View>(R.id.tv_pop_done).setOnClickListener {
                dataMap.clear()
                dataMap["status"] = 1
                onRefreshEvent()
                popWindow.dismiss()
                toolbarTitle.text = "已完成"
            }
            popView.findViewById<View>(R.id.tv_pop_todo).setOnClickListener {
                dataMap.clear()
                dataMap["status"] = 0
                onRefreshEvent()
                popWindow.dismiss()
                toolbarTitle.text = "待办"
            }
        }
    }

    override fun refreshAdapterData(list: List<TodoBean>) {
        list.let { todoList ->
            var hasTodo = false
            for (element in todoList) {
                if (element.status == 0) {
                    hasTodo = true
                    break
                }
            }
            if (hasTodo) LiveEventBus.get("myBadge").post(true)
            else LiveEventBus.get("myBadge").post(false)
        }
        super.refreshAdapterData(list)
    }

    private fun updateTodoById(id: Int, status: Int) {
        mViewModel.updateTodoById(id, status).observe(this, {
            setResult(RESULT_OK)
        })
    }

    private fun deleteTodoById(id: Int) {
        mViewModel.deleteTodoById(id).observe(this, {
            setResult(RESULT_OK)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEAL_SUCCESS && resultCode == RESULT_OK) {
            onRefreshEvent()
        }
    }

    class TodoAdapter : BaseQuickAdapter<TodoBean, BaseViewHolder>(R.layout.item_todo_list),
        LoadMoreModule {

        override fun convert(holder: BaseViewHolder, item: TodoBean) {
            holder.setText(R.id.tv_todo_title, item.title)
                .setText(R.id.item_todo_time, item.dateStr)
            if (item.content.isNotEmpty()) {
                holder.getView<TextView>(R.id.tv_todo_desc).visibility = View.VISIBLE
                holder.setText(R.id.tv_todo_desc, item.content)
            } else {
                holder.getView<TextView>(R.id.tv_todo_desc).visibility = View.INVISIBLE
                holder.setText(R.id.tv_todo_desc, "")
            }
            val done = holder.getView<Button>(R.id.item_todo_done)
            val status = holder.getView<TextView>(R.id.item_todo_status)
            if (item.status == 0) {
                status.visibility = View.VISIBLE
                done.text = context.resources.getString(R.string.done)
            } else if (item.status == 1) {
                status.visibility = View.GONE
                done.text = context.resources.getString(R.string.daiban)
            }
            val imp = holder.getView<TextView>(R.id.item_todo_imp)
            if (item.priority == 1) {
                imp.text = context.resources.getString(R.string.important)
                imp.visibility = View.VISIBLE
            } else imp.visibility = View.GONE
        }
    }
}